<?php

namespace Buu\Modules\EventSystem\Controllers;

use App\Models\ApiUrl;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\MessageBag;

class ApiUrlController extends AdminController
{
    /**
     * title
     * @return string
     */
    protected function title()
    {
        return "API域名管理";
    }

    /**
     * 列表构建
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ApiUrl());
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableBatchActions();
        $grid->column('id', 'ID')->sortable();
        $grid->column('name', '服务名称')->label();
        $grid->column('url', '默认调用域名')->url();
        $grid->column('custom_url', '环境通配符域名')->url();
        return $grid;
    }


    /**
     * 表单.
     *
     * @return Form
     */
    public function form()
    {
        $form = new Form(new ApiUrl());

        $form->text('name', trans('admin.name'))->rules('required');
        $form->text('url', '域名')->rules('required', [
            'required' => '必填字段',
//            'url'   => '必须是http/https',
        ]);
        $form->text('custom_url', '通配符域名')->rules('required', [
            'required' => '必填字段',
//            'url' => '必须是http/https',
        ])->help("仅支持通配符 {{HHZVAR}} 作为变量使用，例如：tapi.{{HHZVAR}}");


        $form->saving(function (Form $form) {
            if (!$id = $form->model()->id) {
                    $count = ApiUrl::query()->where([
                        'url' => $form->url,
                        'custom_url' => $form->custom_url,
                    ])->count('id');
                    if ($count >= 1) {
                        $error = new MessageBag([
                            'title' => '域名已存在！'
                        ]);
                        return back()->with(compact('error'))->withInput();
                    }
                }
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableView();
            $tools->disableDelete();
        });

        return $form;
    }

}